package com.ja.openchat.viewmodels;

import android.app.Application;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.ja.openchat.ui.me.QrCodeFragment;
import com.sahooz.library.CountryPickFragment;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.config.AppConfigInfo;
import com.zy.openchat.core.model.user.UserFullInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.core.model.user.UserMyInfo;
import com.zy.openchat.util.Common;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;


public class PersonalDataViewModel extends BaseViewModel {

    private AppConfigInfo appConfigInfo = null;
    private UserFullInfo userFullInfo;
    public ObservableField<String> userName = new ObservableField<>(UserInfo.getUserInfo().displayName());
    public ObservableField<String> userNameSub = new ObservableField<>(StringUtils.isEmpty(UserInfo.getUserInfo().username) ? "" : (" - @" + UserInfo.getUserInfo().username));
    public ObservableField<String> userPhone = new ObservableField<>(Common.formatPhoneNumber(UserInfo.getUserInfo().phone_number));
    public ObservableField<String> userSignature = new ObservableField<>("");
    public ObservableField<Boolean> showRigthArrow = new ObservableField<>(true);
    public ObservableField<String> countryName = new ObservableField<>(App.getInstanse().getString(R.string.china_text));

    public ObservableField<UserInfo> userAvatar = new ObservableField<>(UserInfo.getUserInfo());
    public UIChangeLiveData mUC = new UIChangeLiveData();

    public final class UIChangeLiveData extends SingleLiveEvent {
        private SingleLiveEvent<Map<String, Object>> showLongClickDialogEvent;
        private SingleLiveEvent<Void> selectPic;
        private SingleLiveEvent<Integer> type;

        public SingleLiveEvent<Integer> getType() {
            return type = new SingleLiveEvent<>();
        }

        public SingleLiveEvent<Void> getSelectPic() {
            return selectPic = new SingleLiveEvent<>();
        }

        public SingleLiveEvent<Map<String, Object>> getShowPaymentPasswordDialogEvent() {
            return showLongClickDialogEvent = new SingleLiveEvent<>();
        }
    }

    public PersonalDataViewModel(@NonNull Application application) {
        super(application);
        appConfigInfo = AppConfigInfo.getAppConfigInfo();
        //默认可修改
        appConfigInfo.permitModifyUserName = true;
        resetUI();
    }

    public void setCountry(UserMyInfo myInfo) {
        this.countryName.set(myInfo.getAddress());
    }

    //选择城市的点击事件
    public BindingCommand countryOnClickCommand = new BindingCommand(() -> {
        Bundle bundle = new Bundle();
        bundle.putBoolean("isShowChinaProvice",true);
        startContainerActivityForResult(CountryPickFragment.class.getCanonicalName(), 1,bundle);
    });
    //二维码的点击事件
    public BindingCommand qrOnClickCommand = new BindingCommand(() -> {
        startContainerActivity(QrCodeFragment.class.getCanonicalName());
    });

    //长按昵称事件
    public BindingCommand nickOnLongClickCommand = new BindingCommand(() -> {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("content", userName.get());
        hashMap.put("type", 1);
        mUC.showLongClickDialogEvent.setValue(hashMap);
    });
    //长按用户名事件
    public BindingCommand nameOnLongClickCommand = new BindingCommand(() -> {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("content", userNameSub.get());
        hashMap.put("type", 2);
        mUC.showLongClickDialogEvent.setValue(hashMap);
    });
    //长按手机号事件
    public BindingCommand phoneOnLongClickCommand = new BindingCommand(() -> {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("content", userPhone.get());
        hashMap.put("type", 3);
        mUC.showLongClickDialogEvent.setValue(hashMap);
    });

    //头像的点击事件
    public BindingCommand headerOnClickCommand = new BindingCommand(() -> {
        mUC.selectPic.call();
    });
    public BindingCommand nameOnClickCommand = new BindingCommand(() -> {
        if (appConfigInfo != null && !appConfigInfo.permitModifyUserName && !TextUtils.isEmpty(userNameSub.get())) {
            return;
        }
        mUC.type.setValue(2);
    });
    public BindingCommand nickOnClickCommand = new BindingCommand(() -> {
        mUC.type.setValue(1);
    });
    public BindingCommand signatureOnClickCommand = new BindingCommand(() -> {
        mUC.type.setValue(3);
    });

    private void resetUI() {
        UserInfo user = UserInfo.getUserInfo();
        userAvatar.set(user);
        userAvatar.notifyChange();
        userName.set(user.displayName());
        String userName = "";
        if (!StringUtils.isEmpty(user.username)) {
            userName = user.username;
        } else {
            userName = "";
        }
        userPhone.set(Common.formatPhoneNumber(user.phone_number));
        userNameSub.set(userName);
        if (appConfigInfo != null) {
            if (appConfigInfo.permitModifyUserName || TextUtils.isEmpty(userName)) {
                showRigthArrow.set(true);
            } else {
                showRigthArrow.set(false);
            }
        }
        if (userFullInfo != null) {
            if(!TextUtils.isEmpty(userFullInfo.bio)){
                userSignature.set(userFullInfo.bio.trim());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(final TgEvent tg_event) {
        switch (tg_event.event) {
            case EUser_Td_UpdateUserInfo: {
                resetUI();
            }
            break;
            case EUser_Td_Contact_Photo_Ok: {
                UserInfo user = (UserInfo) tg_event.data;
                if (user.id == UserInfo.getUserInfo().id) {
                    resetUI();
                }
            }
            break;
        }
    }

    public void loadFullInfo() {
        TelegramManager.getTelegramManager().getUserFullInfo(getApplication(), UserInfo.getUserInfo().id, new TgResultBlock<UserFullInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, UserFullInfo obj) {
                userFullInfo = obj;
                resetUI();
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    public void changeMyPhoto(String localPath) {
        showProgress();
        TelegramManager.getTelegramManager().setMyPhoto(getApplication(), localPath, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getApplication().getString(R.string.request_error)+ obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getApplication().getString(R.string.request_error));
            }
        });
    }
}
